<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/6/006
 * Time: 20:29
 */

namespace app\api\model;


use app\api\service\Token;
use app\lib\exception\CollectException;

class Collect extends BaseModel {

    protected $hidden = ['create_time', 'update_time', 'type', 'article_id'];

    /**
     * 收藏产品
     * @return \think\model\relation\belongsTo
     */
    public function collectProduct() {
        return $this->belongsTo('Product');
    }

    /**
     * 获取用户收藏列表
     * @return \think\Paginator
     */
    public static function collectList() {
        $uid = Token::getCurrentUid();

        $where = [
            'type' => 1,
            'member_id' => $uid
        ];

        $collect = self::with('collectProduct')->where($where)->order('id desc')->paginate(5, true);
        foreach ($collect as $v) {
            $v->collect_product->visible(['id', 'name', 'thumb', 'price', 'for_sale']);
        }

        return $collect;
    }

    /**
     * 收藏商品
     * @param $id
     */
    public static function addCollect($id) {
        $uid = Token::getCurrentUid();

        self::create(['member_id' => $uid, 'product_id' => $id]);
    }

    /**
     * 删除收藏
     * @param $id
     * @throws CollectException
     */
    public static function deleteCollect($id) {
        $uid = Token::getCurrentUid();
        $collect = self::get(['member_id' => $uid, 'id' => $id]);
        if (!$collect) {
            throw new CollectException();
        }
        $collect->delete();
    }

    /**
     * 检查是否有收藏该产品
     * @param $id
     * @return array
     */
    public static function checkCollect($id) {
        $uid = Token::getCurrentUid();
        $collect = self::get(['member_id' => $uid, 'product_id' => $id]);
        if ($collect) {
            return ['code' => 1, 'msg' => '已收藏'];
        } else {
            return ['code' => 0, 'msg' => '未收藏'];
        }
    }
}